/*
 * @Author: Vir
 * @Date: 2021-09-03 14:26:02
 * @Last Modified by: Vir
 * @Last Modified time: 2021-10-10 16:01:13
 */

import StorageDB from 'bsdb';

const BaseDB = new StorageDB({
  storage: localStorage,
  database: 'database',
});

const SiteDB = BaseDB.get('site');

export interface Site {
  _id: string;
  name: string;
  url: string;
  iconUrl?: string;
  count: number;
}

export interface AddSite {
  name: string; //名称
  url: string; //网址
}


class HassApi {

  constructor() {
    try {
      let haPanelIframe = this.querySelector(parent.document.body, [
        "home-assistant",
        "home-assistant-main",
        "ha-panel-iframe"])
      let subpage = haPanelIframe.querySelector("hass-subpage")
      // 新版
      let iframe = subpage.querySelector("iframe");
      let toolbar = subpage.shadowRoot.querySelector('.toolbar')
      subpage.shadowRoot.querySelector('.content').style.height = '100vh'

      iframe.style.position = 'absolute'
      toolbar.style.display = 'none'
      iframe.style.top = '0'
      iframe.style.height = '100%'
    } catch (ex) {
      console.error(ex)
    }
  }

  querySelector(element: any, arr: Array<string>) {
    for (let i = 0, j = arr.length; i < j; i++) {
      const ele = element.querySelector(arr[i])
      if (!ele) return null
      element = ele.shadowRoot
    }
    return element
  }

  async http(type: string, data: any) {
    const ha = parent.document.querySelector('home-assistant') as any;
    if (!ha) throw new Error('请在HomeAsistant中使用')
    return await ha.hass.fetchWithAuth('/homepage-api', {
      method: 'POST',
      body: JSON.stringify({ type: 'site', data: Object.assign({ _type: type }, data) })
    }).then((res: any) => res.json())
  }

  async get() {
    return await this.http('get', {})
  }

  async set(data: any) {
    return await this.http('set', data)
  }

  async del(id: string) {
    return await this.http('del', { id })
  }

  async add(data: any) {
    return await this.http('add', data)
  }

  async addCount(id: string) {
    return await this.http('count', { id })
  }

}

const hassApi = new HassApi()

export const findSite = async () => {
  return await hassApi.get();
};

export const addSite = async (params: AddSite) => {
  return await hassApi.add({ ...params, count: 0 });
};

export const editSite = async (id: string, params: AddSite) => {
  return await hassApi.set({ ...params, id });
};

export const addCount = async (id: string) => {
  return await hassApi.addCount(id);
};

// 删除
export const delSite = async (id: string) => {
  console.log('删除')
  const site = SiteDB.find(id);
  sessionStorage.setItem('site-repeal', JSON.stringify(site));
  return await hassApi.del(id);
};

// 撤销删除
export const repeal = async () => {
  let item = {};
  let session = sessionStorage.getItem('site-repeal');
  if (session !== null) {
    item = JSON.parse(session);
    sessionStorage.removeItem('site-repeal');
  }

  return await hassApi.add(item);
};
